<template>
    <div class="markdown-editor-wrapper">
        <MdEditor
          v-model="content"
          :preview="false"
          @change="handleChange"
          @save="handleSave"
          :height="height"
          @upload-img="handleImgUpload"
        />
    </div>
</template>

<script>
import { ref, watch, defineComponent } from 'vue'
import axios from "axios";
import { ElMessage } from 'element-plus'

export default defineComponent({
    props: {
        value: {
            type: String,
            default: ''
        },
        height: {
            type: String,
            default: '400px'
        },
        editable: {
            type: Boolean,
            default: true
        }
    },
    emits: ['update:value', 'change', 'save'],
    setup(props, { emit }) {
        const content = ref(props.value)

        // 监听外部值变化
        watch(() => props.value, (newVal) => {
            content.value = newVal
        })

        // 监听内部值变化
        watch(() => content.value, (newVal) => {
            emit('update:value', newVal)
        })

        const toolbars = {
            bold: true,
            italic: true,
            header: true,
            underline: true,
            strikethrough: true,
            quote: true,
            ol: true,
            ul: true,
            link: true,
            imagelink: true,
            code: true,
            table: true,
            undo: true,
            redo: true,
            preview: true,
            help: true,
            fullscreen: true
        }

        const handleChange = (value) => {
            emit('change', value)
        }

        const handleSave = (value) => {
            emit('save', value)
        }

        // 图片上传处理
        const handleImgUpload = (files, callback) => {
            const formData = new FormData();
            formData.append("image", files[0]);
            
            axios({
                url: "/tes/markdown/picture",
                method: "post",
                data: formData,
                headers: { "Content-Type": "multipart/form-data" }
            }).then(response => {
                if (response.status == 200) {
                    if (response.data.code == 200) {
                        const url = response.data.data;
                        callback([url]);  // 回调函数，插入图片链接到编辑器
                    } else {
                        ElMessage.error("图片上传失败");
                    }
                }
            }).catch(() => {
                ElMessage.error("图片上传失败");
            });
        }

        return {
            content,
            toolbars,
            handleChange,
            handleSave,
            handleImgUpload
        }
    }
})
</script>

<style>
    .markdown-editor-wrapper {
        width: 100%;
    }

    .mavon-editor-con .op-icon.fa.fa-mavon-trash-o {
        display: none !important;
    }
</style>
